package com.atguigu.headline.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtil {
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    private static DataSource dataSource;

    // 初始化连接池
    static {
        Properties properties = new Properties();
        try (InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties")) {
            if (resourceAsStream == null) {
                throw new RuntimeException("jdbc.properties file not found in classpath");
            }
            properties.load(resourceAsStream);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            throw new RuntimeException("Failed to load jdbc.properties", e);
        } catch (Exception e) {
            throw new RuntimeException("Failed to create Druid DataSource", e);
        }
    }

    // 向外提供连接池的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    // 向外提供连接的方法
    public static Connection getConnection() {
        Connection connection = threadLocal.get();
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            } catch (SQLException e) {
                throw new RuntimeException("Failed to get connection from DataSource", e);
            }
        }
        return connection;
    }

    // 归还连接的方法 (解除和ThreadLocal之间的关联关系)
    public static void releaseConnection() {
        Connection connection = threadLocal.get();
        if (connection != null) {
            threadLocal.remove();
            try {
                connection.setAutoCommit(true);
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException("Failed to close connection", e);
            }
        }
    }
}